package ks.client.controllers.requests;

import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import ks.client.gui.GMGUI;
import ks.client.lobby.Lobby;
import ks.framework.common.Message;
import ks.framework.debug.Debug;
import ks.framework.interfaces.IProcessMessage;

/**
 * Shows how to process Output requests from server.
 * 
 * @author George Heineman
 * @author szutshi
 */
public class TableOutputController implements IProcessMessage {

	/** Lobby being managed. */
	Lobby lobby;
	
	public TableOutputController(Lobby lobby) {
		this.lobby = lobby;
	}

	/** Process message. */
	public boolean process(Message m) {
		Node outputNode = m.contents();
		
		System.out.println("in table output controller");
		
		if (outputNode == null) {
			return false;
		}
		if (!outputNode.getNodeName().equalsIgnoreCase("table-output")) {
			return false;
		}
		
		NamedNodeMap nnp = outputNode.getAttributes();
		
		Node tableNode = nnp.getNamedItem("table");
		Node playerNode = nnp.getNamedItem("player");
		
		if (tableNode == null) {
			return false;
		}
		if (playerNode == null) {
			return false;
		}
		
		int tableNum = Integer.parseInt(tableNode.getNodeValue());
		String player = playerNode.getNodeValue();
		
		NodeList textList = outputNode.getChildNodes();
		
		if (textList.getLength() <= 0) {
			return false;
		}
		
		Node textNode = textList.item(0);
		
		String text = textNode.getTextContent();
		
		GMGUI gui = lobby.getGMGUI(tableNum);
		
		gui.append(player + ": " + text);
		
		return true;
	}

}
